package yxy.game.pm2.active.command.prerogative;

import org.joda.time.DateTime;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.chargeshop;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.ActiveModule_特权商城;
import yxy.game.pm2.active.module.subordinateclass.PrerogativeGoods;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ActiveMessage;
import yxy.game.pm2.message.ActiveMessage.ActPrerogativeInfoRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@MessageType(proto = Command.ActPrerogativeInfo, classtype = ActiveMessage.ActPrerogativeInfoRequest.class)
public class CMD_Active_特权商品_Info extends Command<ActPrerogativeInfoRequest> {

	@Override
	public void execute(MessageSource messageSource, ActPrerogativeInfoRequest request) throws Exception {
		String pcode = messageSource.getTag();
		ActiveMessage.ActPrerogativeInfoResponse.Builder response = ActiveMessage.ActPrerogativeInfoResponse.newBuilder();
		
		ActiveModule_特权商城 am = ActiveModule_特权商城.get(pcode);
		if(am == null) {
			send(messageSource, response, Result.DataError);
			return;
		}
		
		HashMap<Integer, PrerogativeGoods> pgmap = am.getPgmap();
		Map<String, chargeshop> csmap = DataCenter.getAllData(chargeshop.class);
		ArrayList<String> csmapkeys = new ArrayList<String>(csmap.keySet());
		
		for (int i = 0; i < csmapkeys.size(); i++) {
			String key = csmapkeys.get(i);
			chargeshop cs = csmap.get(key);
			
			ActiveMessage.PrerogativeInfo.Builder build = ActiveMessage.PrerogativeInfo.newBuilder();
			
			build.setPgid(cs.getId());
			
			build.setType(cs.getType());
			build.setPurchasetype(cs.getPurchasetype());
			build.setPurchasever(cs.getPurchasever());
			build.setLimittype(cs.getLimittype());

			build.setRebate(cs.getRebate()); //返利倍数
			
			PrerogativeGoods pg = pgmap.get(Integer.valueOf(key));
			if(pg == null) {
				build.setStarttime(new DateTime().getMillis());
				build.setEndtime(new DateTime().getMillis());
			}else {
				long start = pg.getStart() == null?0:pg.getStart().getMillis();
				long end = pg.getEnd() == null?0:pg.getEnd().getMillis();
				build.setStarttime(start);
				build.setEndtime(end);
			}
			
			build.setCanbuy(am.canbuy(cs.getId()));
			
			response.addPginfo(build.build());
		}
		
		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, ActiveMessage.ActPrerogativeInfoResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
	
}
